package main

import (
	"bufio"
	"errors"
	"fmt"
	"functional/fib"
	"os"
)

func main() {
	// tryDefer()
	// tryDefer2()
	writeFile("src/errhandling/static/fib.txt")
	// myError()
}

/**
 * 321, 不怕中间 panic
 */
func tryDefer() {
	defer fmt.Println(1) // defer 相当于栈 FILO
	defer fmt.Println(2)
	fmt.Println(3)
	panic("error occurred")
	return
	fmt.Println(4)
}

func tryDefer2() {
	for i := 0; i < 100; i++ {
		defer fmt.Println(i)
		if i == 30 {
			panic("printed too many")
		}
	}
}

func writeFile(filename string) {
	file, err := os.OpenFile(filename, // 打开文件 os.Create(filename)
		os.O_EXCL|os.O_CREATE|os.O_WRONLY, 0666) // EXCL 存在该文件则打开失败
	// err = errors.New("customer error")
	if err != nil {
		if pathError, ok := err.(*os.PathError); !ok {
			panic(err)
		} else {
			fmt.Printf("%s, %s, %s\n",
				pathError.Op,
				pathError.Path,
				pathError.Err)
		}
		return
	}
	defer file.Close() // 关闭文件

	writer := bufio.NewWriter(file) // 先写入内存,达到指定大小再导入文件
	defer writer.Flush()            // 导入文件

	f := fib.Fibonacci()
	for i := 0; i < 20; i++ {
		fmt.Fprintln(writer, f())
	}

}

func myError() {
	e := errors.New("this is customer error")
	print(e)
}
